<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\GoodsCategory;
use App\Models\Admin\GoodsStandard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Saas,DB,Auth;

class GoodsCategoryController extends AdminController
{
    protected $model;
    protected $unique_id = '';

    public function __construct(GoodsCategory $model)
    {
        parent::__construct();
        $this->model = $model;
    }

    protected $validate_rule = [];

    protected function rules()
    {
        return [
            'title' => [
                'required',
                Rule::unique('goods_category')->where(function ($query) {
                    $query->where('company_id',0);
                })->ignore($this->unique_id)
            ],
        ];
    }

    /**
     * 定义验证错误信息
     */
    protected $err_msg = [
        'title.required' => '内容不能为空',
        'title.unique'=> '内容已经存在了'
    ];

    public function index(BaseRequest $request)
    {
        $categoryList = GoodsCategory::getCategorys();
        return response()->json(['errcode'=>0,'data'=>['category'=>$categoryList],'errmsg'=>'ok']);

    }

//    protected function afterData($info,$requestData)//编辑和添加分类后重新设置列表
//    {
//    }

    public function categoryList(Request $request)//可使用的数据，并且遵循列表的排序
    {
        $category = $this->model->select('id','title','pid','status','company_id')->where('status','>',0)->where(function ($query){
            $query->where('company_id',0);
        })->orderBy('ordid','asc')->get()->groupBy('pid')->toArray();

//        $useCategory = DB::table('goods_category_company')->where('company_id',$this->company_id)->first();
//        $list = json_decode($useCategory->category_ids,true);

        $first = $category[0];
        unset($category[0]);
        $second = $category;

        //处理排序
        if (!empty($list)){
            foreach ($list as $key => $val){
                $list[$key]['status'] = 1;
                $list[$key]['pid'] = 0;
                $list[$key]['isSelect'] = true;
                foreach ($first as $k => $v){
                    if ($v['id'] == $val['id']){
                        unset($first[$k]);
                        continue;
                    }
                }
                if (isset($val['selfNext'])){
                    foreach ($val['selfNext'] as $j => $l){
                        $list[$key]['selfNext'][$j]['status'] = 1;
                        $list[$key]['selfNext'][$j]['pid'] = $val['id'];
                        $list[$key]['selfNext'][$j]['isSelect'] = true;
                        foreach ($second[$val['id']] as $m => $n){
                            if ($n['id'] == $l['id']){
                                unset($second[$val['id']][$m]);
                                continue;
                            }else{
                                $second[$val['id']][$m]['isSelect'] = false;
                                $second[$val['id']][$m]['selfNext'] = [];
                            }
                        }
                    }
                    if (isset($second[$val['id']])){
                        $list[$key]['selfNext'] = array_merge($list[$key]['selfNext'],$second[$val['id']]);
                    }
                }
            }
        }
        if (!empty($first)){
            foreach ($first as $key => $val){
                $first[$key]['isSelect'] = false;
                $first[$key]['selfNext'] = [];
                if (isset($second[$val['id']])){
                    foreach ($second[$val['id']] as $m => $n){
                        $second[$val['id']][$m]['isSelect'] = false;
                        $second[$val['id']][$m]['selfNext'] = [];
                    }
                    $first[$key]['selfNext'] = array_merge($first[$key]['selfNext'],$second[$val['id']]);
                }
            }
            if (empty($list)) $list = [];
            $list = array_merge($list,$first);
        }

        return response()->json(['errcode' => 0,'data'=>['category' => $list], 'errmsg' => 'ok']);
    }

    public function useCategory(Request $request)//导入操作
    {
        $info = DB::table('goods_category_company')->where('company_id',$this->company_id)->first();
        $data = $this->setRequestField($request->all());
        try {
            if (empty($info)){
                $data['company_id'] = $this->company_id;
                $flag = DB::table('goods_category_company')->insert($data);
            }else{
                //dd($data);
                unset($data['company_id']);
                $flag = DB::table('goods_category_company')->where('company_id',$this->company_id)->update($data);
            }

            if (method_exists($this->model,'addLog')){
                $this->model->addLog([],[],6,__FUNCTION__);
            }

            if ($flag){
                return response()->json(['errcode' => 0,'errmsg' => 'ok']);
            }else{
                return response()->json(['errcode' => 40007,'errmsg' => '保存失败,没有修改']);
            }
        }catch (\Exception $exception){
            report($exception);
            return response()->json(['errcode' => 40013,'errmsg' => '系统错误']);
        }

    }

    private function softDelete($id=0)
    {
        $category = DB::table('goods_category_company')->where('company_id',$this->company_id)->first();
        $list = json_decode($category->category_ids,true);

        foreach ($list as $key => $val){
            if ($val['id'] == $id){
                unset($list[$key]);
                break;
            }else{
                foreach ($val['selfNext'] as $k => $v){
                    if ($v['id'] == $id){
                        unset($list[$key]['selfNext'][$k]);
                        if (empty($list[$key]['selfNext'])){
                            unset($list[$key]);
                        }
                        break;
                    }
                }
            }
        }

        $data = $this->consistent($list);//重新定义数组下标，前端不能使用间断的下标

        $category_ids = json_encode($data,JSON_UNESCAPED_UNICODE);

        return DB::table('goods_category_company')->where('company_id',$this->company_id)->update(['category_ids'=>$category_ids]);
    }

    public function delete(BaseRequest $request)//软删除，在列表的删除操作
    {
        $id = $request->id;

        $flag = $this->softDelete($id);

        $info = $this->model->findOrFail($id);
        $this->model->addLog(['title'=>$info->title,'id'=>$id],[],3,__FUNCTION__);

        if ($flag){
            return response()->json(['errcode' => 0,'errmsg' => 'ok']);
        }else{
            return response()->json(['errcode' => 40007,'errmsg' => '修改失败']);
        }

    }

    public function dieDelete(BaseRequest $request)//绝对删除，在导入列表内的删除操作
    {
        $input=$request->all();
        //过滤数据
        $rules=[
            'id'=>  'required|exists:goods_category,id'
        ];
        $validator = Validator::make($input,$rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        //判断是否还有子分类
        $id=$input['id'];
        $is_has_son=$this->model->where('pid',$id)->count();
        if($is_has_son)
        {
            return $this->error(['-1','请先删除该分类下的子分类']);
        }
        $is_use=GoodsStandard::where('category_id',$id)->orWhere('pid',$id)->count();
        if($is_use)
        {
            return $this->error(['-1','该分类在标准库里已被使用，不能删除']);
        }
        try {
            $info = $this->model->find($id);
            if (method_exists($this->model,'addLog')){
                $this->model->addLog($info->toArray(),[],3,'delete');
            }
            GoodsCategory::where('id',$id)->delete();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            return $this->error();
        }

    }

    protected function setRequestField($arr,$type=false){
        if(!$type){
            $arr['company_id'] = 0;
        }
        //过滤字段
        if(isset($arr['_token'])) unset($arr['_token']);
        if (isset($arr['sign'])) unset($arr['sign']);
        if (isset($arr['timeStamp'])) unset($arr['timeStamp']);
        return $arr;
    }

    private function consistent($list):array
    {
        $data = [];
        foreach ($list as $k => $v){//保持前端一致性
            $second = [];
            foreach ($v['selfNext'] as $key => $val){
                $second[] = $val;
            }
            $v['selfNext'] = $second;
            $data[] = $v;
        }
        return $data;
    }

    public function otherData($data,$requestData)
    {
        $pid=isset($requestData['pid'])?$requestData['pid']:0;
        $code_max=$this->model->where('pid',$pid)->where('company_id',0)->max('code');
        if(!$code_max && $pid==0)
        {
            $code='01';
        }
        elseif(is_null($code_max))
        {
            $code_p=$this->model->where('id',$pid)->value('code');
            $code=$code_p.'10';
        }
        elseif($pid==0)
        {
            $code=(string)($code_max+1);
            $code=strlen($code)==1?'0'.$code:$code;
        }
        else
        {
            $code=(string)($code_max+1);
            $code=strlen($code)==3?'0'.$code:$code;
        }
        $data['code']=$code;
        return $data;
    }
}
